﻿using System;
using MvcMall.Core.Commands;
using MvcMall.Core.Contacts.Tasks;
using MvcMall.Framework.UnitOfWork;
using SharpArch.Web.NHibernate;

namespace MvcMall.AdminWeb.Manage.Menu
{
    public partial class SaveMenu : ManageBasePage
    {
        private IAdminMenuTask _adminMenuTask;
        private IAdminModulTask _adminModulTask;
        protected void Page_Load(object sender, EventArgs e)
        {
            ValidatePagePower("SaveAdminMenu");
            _adminMenuTask = GetInstance<IAdminMenuTask>();
            _adminModulTask = GetInstance<IAdminModulTask>();

            if (!IsPostBack)
            {
                var moduls = _adminModulTask.GetAll();
                ddlModuls.DataSource = moduls;
                ddlModuls.DataBind();

                int menuId = 0;
                if (Request.QueryString["Id"] != null && Int32.TryParse(Request.QueryString["Id"], out menuId))
                {
                    var menuInfo = _adminMenuTask.Get(menuId);
                    if (menuInfo == null)
                    {
                        ShowMsg("参数错误", "/Manage/Index");
                        return;
                    }

                    ddlModuls.SelectedIndex =
                        ddlModuls.Items.IndexOf(ddlModuls.Items.FindByValue(menuInfo.AdminModul.Id.ToString()));

                    txtSortOrder.Text = menuInfo.SortOrder.ToString();
                    txtMenuName.Text = menuInfo.MenuName;
                    txtLinkUrl.Text = menuInfo.LinkUrl;
                    lblMenuId.Text = menuId.ToString();
                }
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            var menuName = txtMenuName.Text.Trim();
            var linkUrl = txtLinkUrl.Text.Trim();
            var soreOrder = Convert.ToInt32(txtSortOrder.Text.Trim());

            if (string.IsNullOrEmpty(menuName) || string.IsNullOrEmpty(linkUrl))
            {
                ShowMsg("输入错误");
                return;
            }

            var cmd = new SaveAdminMenuCommand
                          {
                              LinkUrl = linkUrl,
                              MenuId =
                                  string.IsNullOrEmpty(lblMenuId.Text) ? (int?)null : Convert.ToInt32(lblMenuId.Text),
                              MenuName = menuName,
                              ModulId = Convert.ToInt32(ddlModuls.SelectedValue),
                              SortOrder = soreOrder
                          };

            using (var work = UnitOfWork.Begin())
            {
                if (_adminMenuTask.Save(cmd) != null)
                {
                    work.Commit();
                    ShowMsg("保存菜单成功", "/Manage/Menu/Index.aspx");
                }
                else
                    ShowMsg("保存菜单失败");
            }
        }
    }
}